package com.gdufe.firesafe.service.impl;

import cn.hutool.core.io.FileUtil;
import com.gdufe.firesafe.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Service("fileService")
public class FileServiceImpl implements FileService {
    //文件保存的目录，user.dir是项目根目录
    private static final String DIR_PATH = System.getProperty("user.dir") + File.separator + "files";

    @Value("${ip:localhost}")
    //@Value(“${xxxx}”)注解从配置文件读取值的用法，也就是从application.yml / application.properties文件中获取值
    //假如application当中读不到值，那么就使用localhost，也可以不设置默认值，冒号后面不写值，避免配置文件没有设置值而启动报错
    String ip;

    @Value("${gateway.port:8080}")
    String port;

    @Override
    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//带后缀的文件名
//        String mainName = FileUtil.mainName(originalFilename);//不带后缀的文件名
//        String extName = FileUtil.extName(originalFilename);//文件后缀名
        String fileName=originalFilename;
        String filePath = DIR_PATH + File.separator + originalFilename;//文件保存的路径，File.separator在windows中相当于"\\"，在linux中相当于"/"
        File saveFile = new File(filePath);
        //若文件保存的目录不存在，则创建
        if (!saveFile.getParentFile().exists())
            saveFile.getParentFile().mkdirs();
        //若文件已存在，则重命名
        if (saveFile.exists()) {
            fileName=System.currentTimeMillis()+ "_" +originalFilename;
            filePath = DIR_PATH + File.separator + fileName;
            saveFile = new File(filePath);
        }
        //存储到本地硬盘
        file.transferTo(saveFile);
        String url = "http://" + ip + ":" + port + "/user/file/download/" + fileName;
        return url;
    }

    @Override
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//使文件直接下载，而不是在浏览器中打开
        String filePath=DIR_PATH+File.separator+fileName;
        if(!FileUtil.exist(filePath))
            throw new RuntimeException("文件不存在");
        //读取文件成字节流
        byte[] bytes= FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
